package cn.lg.soar.system.auth.service;

import cn.lg.soar.common.util.data.DataUtil;
import cn.lg.soar.system.api.enums.OrgTypeEnum;
import cn.lg.soar.system.auth.entity.Org;
import cn.lg.soar.system.auth.model.OrgSelectorDTO;
import cn.lg.soar.system.config.AuthCacheKey;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@RefreshScope
public class OrgSelectorService {

    @Autowired
    private IOrgService orgService;

    public List<OrgSelectorDTO> ids(Collection<Long> ids) {
        return toDto(
                orgService.listByIds(ids, AuthCacheKey.ORG_BY_ID)
        );
    }

    public List<OrgSelectorDTO> query(String keyword, OrgTypeEnum[] types) {
        return toDto(
                orgService.page(
                        new Page<>(1, 500),
                        Wrappers.<Org>lambdaQuery()
                                .select(Org::getId, Org::getName, Org::getParentId, Org::getType)
                                .eq(Org::getDisabled, false)
                                .in(DataUtil.isValuable(types), Org::getType, (Object[]) types)
                                .like(Org::getName, keyword)
                ).getRecords()
        );
    }

    public List<OrgSelectorDTO> org(Long parentId) {
        return toDto(
                orgService.list(
                        Wrappers.<Org>lambdaQuery()
                                .select(Org::getId, Org::getName, Org::getParentId, Org::getType, Org::getLeftNo, Org::getRightNo)
                                .eq(Org::getDisabled, false)
                                .eq(Org::getParentId, parentId)
                )
        );
    }

    private List<OrgSelectorDTO> toDto(List<Org> orgs) {
        Set<Long> ids = orgs.stream().map(Org::getParentId).collect(Collectors.toSet());
        Map<Long, List<String>> map = orgService.nameLinkByIds(ids);

        return orgs.stream()
                .map(x -> {
                    OrgSelectorDTO dto = OrgSelectorDTO.from(x);
                    dto.setLink(map.get(x.getParentId()));
                    return dto;
                })
                .collect(Collectors.toList());
    }
}
